import axios from 'axios'
import env from './env'
import router from '@/router'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === 'production'
      ? env.prod.baseUrl
      : process.env.NODE_ENV === 'test'
      ? env.test.baseUrl
      : env.dev.baseUrl,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
  settimeout: 50000,
})
service.interceptors.request.use(
  config => {
    if (localStorage.getItem('Authorization')) {
      config.headers.Authorization = localStorage.getItem('Authorization')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response.headers.authorization) {
      localStorage.setItem('Authorization', response.headers.authorization)
    }
    if (response.status && response.status === 200) {
      if (response.data.code === 0) {
        return response.data
      } else if (
        response.data.code === '6017' ||
        response.data.code === '6014' ||
        response.data.code === '9013' ||
        response.data.code === '9103'
      ) {
        Message.error('登录已过期，请重新登录！')
        localStorage.removeItem('Authorization')
        router.push('/')
      }
      return Promise.resolve(response.data)
    }
  },
  error => {
    return Promise.reject(error)
  }
)
export default service
